package app1.rapidsquare.com.fragment;

import android.app.ProgressDialog;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.widget.Toast;

import org.apache.http.entity.StringEntity;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.activity.R;
import app1.rapidsquare.com.classes.UserDetails;
import app1.rapidsquare.com.core.ConnectionDetector;

/**
 * Created by Hikmat on 07.08.2014.
 */
public abstract class AgileFragment extends Fragment {

    private ConnectionDetector mConnectionDetector;
    private Utility.RequestMethodType mRequestMethodType;
    private volatile String mUrl;
    protected StringEntity mHttpEntity;
    protected ProgressDialog progressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mConnectionDetector = new ConnectionDetector(getActivity());
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Please wait");
    }

    @Override
    public void onResume() {
        super.onResume();
        getActivity().registerReceiver(
                mConnectionDetector,
                new IntentFilter(
                        android.net.ConnectivityManager.CONNECTIVITY_ACTION));
    }

    @Override
    public void onPause() {
        super.onPause();
        getActivity().unregisterReceiver(mConnectionDetector);
    }

    protected UserDetails getUserSession() {
        return Utility.getUserSession(getActivity());
    }

    protected boolean IsAuthentication() {
        return getUserSession() != null
                && !Utility.isNullOrEmpty(getUserSession().UserToken)
                && !Utility.isNullOrEmpty(getUserSession().Code);
    }

    protected boolean IsAvailableInternet() {
        return mConnectionDetector.getConnectingStatus();
    }

    protected void setUrl(String mUrl) {
        this.mUrl = mUrl;
    }

    protected String getUrl() {
        return this.mUrl;
    }


    public Utility.RequestMethodType getRequestMethodType() {
        return mRequestMethodType;
    }

    public void setRequestMethodType(Utility.RequestMethodType mRequestMethodType) {
        this.mRequestMethodType = mRequestMethodType;
    }

    protected synchronized void SendRequest(boolean showDialog) {

        if (IsAvailableInternet()) {
            if (showDialog)
                progressDialog.show();

            new AsyncTask<Void, Void, String>() {

                @Override
                protected String doInBackground(Void... params) {
                    //return ConnectServer();
                    return Utility.ConnectServer(getUrl(), getRequestMethodType(), mHttpEntity);
                }

                @Override
                protected void onPostExecute(String result) {
                    getResponce(result);
                    if (progressDialog != null)
                        progressDialog.dismiss();
                }
            }.execute();
        }
    }

    protected abstract void getResponce(String result);

    private String ConnectServer() {
        try {

            URL url = new URL(this.mUrl);
            HttpURLConnection connection = null;

            /*if (url.getProtocol().toLowerCase().equals("https")) {
                Utility.trustAllHosts();
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                httpsURLConnection.setHostnameVerifier(Utility.DO_NOT_VERIFY);
                connection = httpsURLConnection;
            } else {*/
            connection = (HttpURLConnection) url
                    .openConnection();
            //}

            connection.setRequestMethod(getRequestMethodType().name());
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-type", "application/json");
            connection.setRequestProperty("charset", "utf-8");
            connection.setConnectTimeout(3000);

            if (getRequestMethodType() == Utility.RequestMethodType.POST) {
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setInstanceFollowRedirects(false);
                connection.setUseCaches(false);

                DataOutputStream wr = new DataOutputStream(
                        connection.getOutputStream());
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        mHttpEntity.getContent(), "utf-8"));
                StringBuilder requestStringBuilder = new StringBuilder();
                String readLine;
                while ((readLine = in.readLine()) != null) {
                    requestStringBuilder.append(readLine);
                }
                wr.writeChars(requestStringBuilder.toString());
                wr.flush();
                wr.close();
                in.close();
            }

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK)

            {
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                return response.toString();

            } else {

                Toast.makeText(getActivity(), getResources().getString(
                        R.string.server_connection_is_not_available), Toast.LENGTH_SHORT).show();

            }
        } catch (Exception ex) {
            Utility.Log("Error is connection to the service", ex);
            return null;
        }

        return null;
    }
}
